//
//  MainTableViewController.swift
//  微博项目
//
//  Created by 原晓桢 on 15/11/3.
//  Copyright © 2015年 itcast.cn. All rights reserved.
//

import UIKit

class MainTableViewController: UITabBarController {

    /**
    按钮点击事件(响应者链条)
    找到事件后父类通过sendaction方法来向上传递
    需要添加 @objc
    */
    @objc private func clickComposedButton() {
        print("点点点")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //刷新子控制器
        addChildViewControllers()
        
        //刷新按钮
        setupComposedButton()
    }
    
    //解决加号按钮不能显示的问题
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        tabBar.bringSubviewToFront(composedButton)
    }
    
    ///懒加载
    private lazy var composedButton: UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")
}

//MARK: - 设置界面
extension MainTableViewController {
    
    ///设置加号按钮
    private func setupComposedButton(){
        
        // 1.添加按钮
        tabBar.addSubview(composedButton)
        
        // 2.设置按钮frame
        let count = childViewControllers.count
        
        let wth = tabBar.bounds.width / CGFloat(count) - 1
        composedButton.frame = CGRectInset(tabBar.bounds, wth * 2, 0)
        
        // 3.添加监听方法
        composedButton.addTarget(self, action: nil, forControlEvents: .TouchUpInside)
    }
    
    ///添加所有子控制器
    private func addChildViewControllers() {
        
        //设置按钮颜色,用属性改变颜色代替用图片渲染,可以提升性能
        tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    ///添加子控制器
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        
        //设置标题
        vc.title = title
        //设置图像
        vc.tabBarItem.image = UIImage(named: imageName)
        //设置导航控制器
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
}
